/*
 * @Copyright: Copyright (c) 2030 吴周海
 * @Author: wzh200x@126.com
 * @Date: 2025-10-20 10:28:34
 * @LastEditors: wzh200x@126.com
 * @LastEditTime: 2025-10-22 15:25:25
 * @FilePath: \gogamewebserver\goGameWebServer\internal\platform\platformKuaiShou.go
 * @Description: 文件功能描述
 */
package platform

import (
	"bytes"
	"encoding/json"
	"fmt"
	"goGameWebServer/internal/common/config"
	"goGameWebServer/internal/common/logger"
	"goGameWebServer/internal/common/utils"
	"io"
	"net/http"

	"github.com/gogf/gf/v2/util/gconv"
)

// 微信登录返回的会话信息
type KuaiShouSession struct {
	OpenID     string `json:"open_id"`
	SessionKey string `json:"session_key"`
	Result     int32  `json:"result"`
	ErrorMsg   string `json:"error_msg"`
}

type PlatformKuaiShou struct {
	PlatformBase
}

func (p *PlatformKuaiShou) Login(code string, option *config.PlatformOption) (output map[string]interface{}, err error) {
	// 1. 通过code获取微信会话信息
	session, err := p.GetSession(option.AppId, option.AppSecret, code)
	if err != nil {
		return output, err
	}
	output = make(map[string]interface{})
	output["open_id"] = session.OpenID
	output["session_key"] = session.SessionKey
	return output, nil
}

// 通过code获取微信会话信息
func (p *PlatformKuaiShou) GetSession(appid string, appSecret string, code string) (*KuaiShouSession, error) {
	url := fmt.Sprintf("https://open.kuaishou.com/game/minigame/jscode2session?app_id=%s&app_secret=%s&js_code=%s&grant_type=authorization_code",
		appid, appSecret, code)

	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var session KuaiShouSession
	if err := json.Unmarshal(body, &session); err != nil {
		return nil, err
	}

	if session.Result != 1 {
		return nil, fmt.Errorf("快手API错误: %d ", session.Result)
	}

	return &session, nil
}

func (p *PlatformKuaiShou) Report(params map[string]interface{}, option *config.PlatformOption) (re map[string]interface{}, err error) {
	re = make(map[string]interface{})
	// 构建请求参数
	reqParams := map[string]interface{}{
		"event_type":  params["action_code"],
		"callback":    params["action_finish_channel"],
		"event_props": params["event_props"],
		"event_time":  utils.GetNowTimestampSecond(),
	}
	// 发送POST请求
	// 将参数转换为JSON
	jsonData, err := json.Marshal(reqParams)
	if err != nil {
		logger.LoggerIns().Errorf("参数序列化失败: %v\n", err)
		return re, err
	}
	resp, err := http.Post("https://ad.partner.gifshow.com/track/activate?",
		"application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		logger.LoggerIns().Errorf("快手行动码上报请求失败: %v\n", err)
		return re, err
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		logger.LoggerIns().Errorf("读取快手行动码上报响应失败: %v\n", err)
		return re, err
	}
	// 解析响应体
	var response map[string]interface{}
	err = json.Unmarshal(body, &response)
	if err != nil {
		logger.LoggerIns().Errorf("响应体解析失败: %v\n", err)
		return re, err
	}
	// 检查响应状态
	if gconv.String(response["code"]) != "0" {
		logger.LoggerIns().Errorf("快手行动码上报失败: %v\n", response)
		logger.LoggerIns().Errorf("快手行动码上报内容: %v\n", params)
	}
	re["code"] = response["code"]
	re["msg"] = response["msg"]
	re["result"] = body
	return nil, nil
}

func NewPlatformKuaiShou() *PlatformKuaiShou {
	return &PlatformKuaiShou{
		PlatformBase: PlatformBase{},
	}
}
